package com.itheima.web.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.domain.Question;
import com.itheima.domain.Result;
import com.itheima.service.QuestionService;
import com.itheima.utils.BeanUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 *  该Servlet处理所有的CRUD操作：
 *  分页查询：http://localhost:8080/heima_mm/store/question/findByPage?currentPage=1&pageSize=5
 *  新增：http://localhost:8080/heima_mm/store/question/save
 *  编辑：http://localhost:8080/heima_mm/store/question/edit
 *  删除：http://localhost:8080/heima_mm/store/question/delete
 */
@WebServlet("/store/question/*")
public class QuestionServlet extends BaseServlet {

    /**
     * 导出excel表格
     * @param request
     * @param response
     */
    private Result toExport(HttpServletRequest request, HttpServletResponse response) throws IOException {
        QuestionService questionService = ac.getBean("questionService", QuestionService.class);
        //需求：在servie中读取excel模版，将数据些到excel中，然后在servlet使用文件下载技术发送给客户端
        try {
            //1 设置Content-disposition响应头
            response.setHeader("Content-disposition","attachment;filename=question.xlsx");
            //2 调用service层方法，报表导出
            questionService.toExport(response.getOutputStream());
            return new Result(true,MessageConstant.QUESTION_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(true,MessageConstant.QUESTION_EXPORT_FAIL);
        }
    }
    /**
     * 处理文件上传
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    private Result upload(HttpServletRequest request, HttpServletResponse response) throws IOException{
        try {
            //1 创建DiskFileItemFactory磁盘工厂对象
            DiskFileItemFactory factory=new DiskFileItemFactory();
            //2 创建ServletFileUpload文件上传核心对象
            ServletFileUpload fileUpload=new ServletFileUpload(factory);
            //3 解析请求，获取所有表单项FileItems
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            //对于我们的项目而已，其实每次只会上传一张图片
            FileItem fileItem = fileItems.get(0);
            //4 将图片写到服务器硬盘中
            //4.1 获取保存文件的目录
            String realPath = getServletContext().getRealPath("/upload");
            //4.2 获取文件名
            String filename = fileItem.getName(); //abc.jpg
            //需求：保证图片名称唯一，使用UUID生成一个唯一的字符串作为文件名
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //获取原文件的后缀名
            String suffix = filename.substring(filename.lastIndexOf(".")); // .jpg 或者 .png
            //组合新的文件名
            filename=uuid+suffix;
            //4.3 将图片写到磁盘中
            fileItem.write(new File(realPath,filename));
            return new Result(true,MessageConstant.UPLOAD_QUESTIONIMG_SUCCESS,filename);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.UPLOAD_QUESTIONIMG_FAIL);
        }
    };
    /**
     * 根据查询所有信息的方法
     * @param request
     * @param response
     */
    private Result findAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
        QuestionService questionService = ac.getBean("questionService", QuestionService.class);
        try {
            //1 调用service，根据id查询信息
            List<Question> list=questionService.findAll();
            //2 响应结果到客户端
            return new Result(true,MessageConstant.QUERY_QUESTION_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_QUESTION_FAIL);
        }
    }
    /**
     * 删除信息的方法
     * @param request
     * @param response
     */
    private Result delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        QuestionService questionService = ac.getBean("questionService", QuestionService.class);
        try {
            //1 获取请求参数并封装
            String[] ids = BeanUtil.fillBeanFromJson(request, String[].class);
            //2 调用service层方法，批量删除数据
            questionService.delete(ids);
            //3 响应结果
            return new Result(true,MessageConstant.DELETE_QUESTION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_QUESTION_FAIL);
        }
    }

    /**
     * 修改数据的方法
     * @param request
     * @param response
     */
    private Result edit(HttpServletRequest request, HttpServletResponse response) throws IOException {
        QuestionService questionService = ac.getBean("questionService", QuestionService.class);
        try {
            //1 获取请求参数并封装
            Question question = BeanUtil.fillBeanFromJson(request, Question.class);
            //2 调用service层方法，修改数据
            questionService.update(question);
            //3 响应结果
            return new Result(true,MessageConstant.EDIT_QUESTION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_QUESTION_FAIL);
        }
    }

    /**
     * 根据id查询信息的方法
     * @param request
     * @param response
     */
    private Result findById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        QuestionService questionService = ac.getBean("questionService", QuestionService.class);
        try {
            //1 获取请求参数 id
            String id = request.getParameter("id");
            //2 调用service，根据id查询信息
            Question question=questionService.findById(id);
            //3 响应结果到客户端
            return new Result(true,MessageConstant.QUERY_QUESTION_SUCCESS,question);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_QUESTION_FAIL);
        }
    }

    /**
     * 保存信息
     * @param request
     * @param response
     */
    private Result save(HttpServletRequest request, HttpServletResponse response) throws IOException {
        QuestionService questionService = ac.getBean("questionService", QuestionService.class);
        try {
            //1 获取请求参数并封装
            Question question = BeanUtil.fillBeanFromJson(request, Question.class);
            //2 调用service层方法，保存数据
            questionService.save(question);
            //3 响应结果
            return new Result(true,MessageConstant.SAVE_QUESTION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.SAVE_QUESTION_FAIL);
        }
    }

    /**
     * 处理分页查询的请求
     * @param request
     * @param response
     */
    private Result findByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        QuestionService questionService = ac.getBean("questionService", QuestionService.class);
        try {
            //1 获取请求参数 currentPage和pageSize
            String currentPageStr = request.getParameter("currentPage");
            String pageSizeStr = request.getParameter("pageSize");
            //2 非空校验并赋默认值
            int currentPage=1,pageSize=5;
            if(!StringUtils.isBlank(currentPageStr)){
                currentPage=Integer.parseInt(currentPageStr);
            }
            if(!StringUtils.isBlank(pageSizeStr)){
                pageSize=Integer.parseInt(pageSizeStr);
            }
            //3 调用service层方法，执行查询得到pageInfo
            PageInfo<Question> info = questionService.findByPage(currentPage, pageSize);
            //4 响应结果
           return new Result(true, MessageConstant.QUERY_QUESTION_SUCCESS,info);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_QUESTION_FAIL);
        }
    }
}
